package com.foodorder.service;

import com.foodorder.entity.Category;
import com.foodorder.repository.CategoryRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分类服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryService {
    
    private final CategoryRepository categoryRepository;
    
    /**
     * 根据店铺ID获取启用的分类列表
     */
    public List<Category> getEnabledCategoriesByStoreId(Long storeId) {
        return categoryRepository.findByStoreIdAndEnabledOrderBySortOrderAsc(storeId, true);
    }
    
    /**
     * 根据店铺ID获取所有分类列表
     */
    public List<Category> getAllCategoriesByStoreId(Long storeId) {
        return categoryRepository.findByStoreId(storeId);
    }
    
    /**
     * 根据ID获取分类
     */
    public Category getCategoryById(Long id) {
        return categoryRepository.findById(id).orElse(null);
    }
    
    /**
     * 保存分类
     */
    public Category saveCategory(Category category) {
        return categoryRepository.save(category);
    }
    
    /**
     * 删除分类
     */
    public void deleteCategory(Long id) {
        categoryRepository.deleteById(id);
    }
    
    /**
     * 获取所有启用的分类
     */
    public List<Category> getAllEnabledCategories() {
        return categoryRepository.findByEnabledOrderBySortOrderAsc(true);
    }
    
    /**
     * 根据名称搜索分类
     */
    public List<Category> searchCategoriesByName(String name) {
        return categoryRepository.findByNameContaining(name);
    }
    
    /**
     * 获取有商品的分类
     */
    public List<Category> getCategoriesWithProducts() {
        return categoryRepository.findCategoriesWithProducts(true);
    }
    
    /**
     * 统计分类下的商品数量
     */
    public long countProductsInCategory(Long categoryId) {
        return categoryRepository.countProductsByCategoryId(categoryId);
    }
    
    /**
     * 管理端分页查询分类
     */
    public Page<Category> findCategoriesForAdmin(String keyword, String status, Long storeId, Pageable pageable) {
        Specification<Category> spec = Specification.where(null);
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            spec = spec.and((root, query, criteriaBuilder) -> 
                criteriaBuilder.like(root.get("name"), "%" + keyword + "%")
            );
        }
        
        if (status != null && !status.trim().isEmpty()) {
            boolean enabled = "ENABLED".equalsIgnoreCase(status);
            spec = spec.and((root, query, criteriaBuilder) -> 
                criteriaBuilder.equal(root.get("enabled"), enabled)
            );
        }
        
        if (storeId != null) {
            spec = spec.and((root, query, criteriaBuilder) -> 
                criteriaBuilder.equal(root.get("storeId"), storeId)
            );
        }
        
        return categoryRepository.findAll(spec, pageable);
    }
    
    /**
     * 更新分类状态
     */
    @Transactional
    public void updateStatus(Long id, String status) {
        Category category = categoryRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        boolean enabled = "ENABLED".equalsIgnoreCase(status);
        category.setEnabled(enabled);
        categoryRepository.save(category);
    }
    
    /**
     * 更新分类排序
     */
    @Transactional
    public void updateSortOrder(Long id, Integer sortOrder) {
        Category category = categoryRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        category.setSortOrder(sortOrder);
        categoryRepository.save(category);
    }
    
    /**
     * 根据店铺ID查找分类（兼容方法）
     */
    public List<Category> findByStoreId(Long storeId) {
        return categoryRepository.findByStoreId(storeId);
    }
    
    /**
     * 根据ID查找分类（兼容方法）
     */
    public Category findById(Long id) {
        return categoryRepository.findById(id).orElse(null);
    }
    
    /**
     * 保存分类（兼容方法）
     */
    public Category save(Category category) {
        return categoryRepository.save(category);
    }
    
    /**
     * 根据ID删除分类
     */
    @Transactional
    public void deleteById(Long id) {
        categoryRepository.deleteById(id);
    }
    
    /**
     * 批量删除分类
     */
    @Transactional
    public void deleteByIds(List<Long> ids) {
        categoryRepository.deleteAllById(ids);
    }
} 